//
//  Photo+Ex.swift
//  App
//
//  Created by LXF on 2018/9/21.
//  Copyright © 2018年 LXF. All rights reserved.
//

import Foundation
import FastComponent
import Photos
import RxSwift
import RxCocoa



public extension XXExtension where Base:PHAsset{
    /// cropHeightRatio  宽 / 高
    func requestImage(cropRect: CGRect? = nil, cropHeightRatio:CGFloat? = nil) -> Observable<(PHAsset, UIImage)>{
        
        return Observable.create({ (observer) -> Disposable in
            DispatchQueue.global(qos: .default).async(execute: {
                
                let options = PHImageRequestOptions()
                options.deliveryMode = .highQualityFormat
                options.isNetworkAccessAllowed = true
                
                var targetSize:CGSize = CGSize(width: self.base.pixelWidth, height: self.base.pixelHeight)
                
                if let cropRect = cropRect{
                    options.normalizedCropRect = cropRect
                    
                    if let cro = cropHeightRatio{
                        let targetWidth  = floor(CGFloat(self.base.pixelWidth) * cropRect.width)
                        let targetHeight = floor(CGFloat(self.base.pixelHeight) * cropRect.height)
                        let dimensionW   = max(min(targetHeight, targetWidth), 1024 * UIScreen.main.scale)
                        let dimensionH   = dimensionW * cro
                        targetSize   = CGSize(width: dimensionW, height: dimensionH)
                    }
                }
                
                options.resizeMode = .exact
                
                PHImageManager.default().requestImage(
                    for: self.base, targetSize: targetSize,
                    contentMode: .aspectFill, options: options) { result, info in
                        DispatchQueue.main.async(execute: {
                            guard let result = result else {
                                observer.onError(RxError.noElements)
                                return
                            }
                            observer.onNext((self.base, result))
                            observer.onCompleted()
                        })
                }
            })
            
            
            return Disposables.create()
        })
    }
}

